package com.putige.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.putige.reggie.common.R;
import com.putige.reggie.entity.Orders;
import com.putige.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders) {

        boolean play = orderService.submit(orders);

        if (play == false) {
            return R.error("下单失败");
        }
        return R.success("支付成功!");
    }


    @GetMapping("/userPage")
    public R<Page<Orders>> userPage(Integer page, Integer pageSize) {
        //检查参数
        if (page <= 0 || pageSize <= 0) {
            return R.error("参数错误!");
        }

        //查看订单
        Page<Orders> user = orderService.userOrder(page, pageSize);
        if (user == null) {
            return R.error("没有查询到订单!");
        }
        return R.success(user);
    }

    /**
     * 客户端 查看订单信息
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    @GetMapping("/page")
    public R<Page<Orders>> page(Integer page, Integer pageSize, String number, String beginTime, String endTime) throws ParseException {
        //检查参数
        if (page <= 0 || pageSize <= 0) {
            return R.error("参数错误!");
        }

        //查看订单
        Page<Orders> user = orderService.userOrders(page, pageSize, number, beginTime, endTime);
        if (user == null) {
            return R.error("没有查询到订单!");
        }
        return R.success(user);
    }


    @PutMapping
    public R update(@RequestBody Orders orders) {
        //检查参数
        if (orders == null) {
            return R.error("参数异常");
        }
        //通过订单id修改订单状态
        Long id = orders.getId();
        if (id == null) {
            return R.error("id不存在");//id为空
        }
        //得到传入的状态
        Integer status = orders.getStatus();

        //根据id查询到一个对象
        Orders one = orderService.getById(id);
        if (one == null) {
            return null;
        }
        //将最新的状态给到对象
        one.setStatus(status);
        orderService.updateById(one);

       /* LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getId, orders.getId());
        orderService.update(orders, wrapper);*/
        return R.success("状态修改成功!");
    }
}